import {Component, Input, OnInit} from '@angular/core';
import {GridOptions} from '@ag-grid-community/core';
import {ApiService} from '@core/services/http/api.service';
import {GridConfigService} from '@core/config/grid-config.service';
import {ApesMessageService} from '@shared/apes/message';

@Component({
  selector: 'grid',
  templateUrl: './grid.component.html',
  styleUrls: ['./grid.component.scss']
})
export class GridComponent implements OnInit {

  name: string = 'GridComponent';
  params: any;
  mateData: any;

  tabList: any = [];
  rowData: any[] = [];
  gridOptions: GridOptions;
  data: any[] = [];
  columnDefs: any[] = [];
  localeText: any;
  height: string = '200px';

  /** 分页器 **/
  total = 0;
  pageSize = 20;
  currentPage = 1;

  button = [
    { name: '删除', bot: 'delete' },
    { name: '编辑', bot: 'default' }
   ];

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private msg: ApesMessageService,) {
    this.localeText = gridConfigService.getLocaleText();
    this.getcolumnDefsData();
  }


  ngOnInit() {
    console.log("GridComponent----> params", this.params);
    this.getTableFieldData();
  }

  /** 页码改变事件 **/
  onPageIndexChange() {
    this.getTableFieldData();
    console.log(this.rowData.length);
    console.log(this.currentPage)
  }

  /** 表单数据及grid数据 **/
  getTableFieldData() {
    let data = {
      'page': this.currentPage, 'size': this.pageSize,
      'COMPANY_ID': '1001'
    };
    this.apiService.post('ledger.main.list', {'body': JSON.stringify(data)}).subscribe(data => {
      if (data) {
        this.total = data.length + 1;
        this.rowData = data;
        if (this.rowData.length === 0) {
          this.msg.info(`未找到满足条件的数据`);
        }
      } else {
        this.msg.info(data.msg);
      }
    })
  }

  /** 获取grid头部数据 **/
  getcolumnDefsData() {
    this.apiService.post('ledger.account.list', {}).subscribe(
      data => {
        this.columnDefs = data.map(item => {
          return {headerName: item.name, field: item.id, width: 120, cellRenderer: this.toFixed};
        });
      });
  }

  /** 数字保留两位小数点 **/
  toFixed(params) {
    let key = params.colDef.field;
    let data = params.data[key];
    if (data !== undefined) {
      data = data.toFixed(2);
    }
    return data;
  }


}
